package com.lyl.example.common.config;

import cn.hutool.json.JSONUtil;
import com.lyl.example.common.annotation.IgnoreResponseWrapper;
import com.lyl.example.common.result.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Arrays;

/**
 * @author Mr.Luo
 * @date 2022-07-06 10:24
 * @desc 全局响应处理
 */
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
    /**
     * 排除的swagger的请求
     */
    private static final String[] EXCLUDE = {
            "Swagger2Controller",
            "Swagger2ControllerWebMvc",
            "ApiResourceController"
    };

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //如果接口本身返回的就是Result,或者方法、类上携带 IgnoreResponseWrapper 注解的不包装返回值类型
        return !(methodParameter.getParameterType().isAssignableFrom(Result.class)
                || methodParameter.hasMethodAnnotation(IgnoreResponseWrapper.class)
                || methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseWrapper.class)
                || Arrays.asList(EXCLUDE).contains(methodParameter.getDeclaringClass().getSimpleName())
        );
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof String) {
            return JSONUtil.toJsonStr(Result.ok(o));
        } else if (o instanceof Result) {
            return o;
        }
        return Result.ok(o);
    }
}
